package tech.heptagram.staff.cas.config.cas.urlFileter;


import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import tech.heptagram.staff.cas.domain.po.Menu;
import tech.heptagram.staff.cas.domain.po.Role;
import tech.heptagram.staff.cas.service.staff.CasMenuService;
import tech.heptagram.staff.cas.service.staff.CasRoleService;

/**
 * 获取被拦截URL所需要的全部权限
 */
@Component
public class URLFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    private static final Integer HAS_PATH_TYPE = 1;

    @Resource
    private CasMenuService casMenuService;

    @Resource
    private CasRoleService casRoleService;

    private String DEFAULT_ROLE_PREFIX = "ROLE_";


    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        final HttpServletRequest request = ((FilterInvocation) object).getRequest();

        String servletPath = request.getServletPath();
        List<Menu> menus = casMenuService.findByPath(servletPath);
        if (CollectionUtils.isEmpty(menus)) {
            return null;
        }

        Menu menu = menus.get(0);
        List<Role> roles = casRoleService.findRolesByMenuId(menu.getId());

        Collection<ConfigAttribute> configAttributes = new HashSet<>();

        for (Role role : roles) {
            ConfigAttribute attribute = new SecurityConfig(DEFAULT_ROLE_PREFIX + role.getId().toString());
            configAttributes.add(attribute);
        }

        return configAttributes;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
